﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace WebFrontEnd
{
    public static class YorKinHTMLHelper
    {
        public static ListItemCollection GetListItemsFromEnum(Type enumType)
        {
            if (!enumType.IsEnum) throw new ArgumentException("type must be that of an enum", "type");
            ListItemCollection items = new ListItemCollection();
            // break down the enumerator items into key/value pairs
            string[] names = Enum.GetNames(enumType);
            Array values = Enum.GetValues(enumType);
            // piece together the key/pairs into the listitem collection
            for (int i = 0; i <= names.Length - 1; i++)
            {
                items.Add(new ListItem(enumType.GetDescriptionForEnum(values.GetValue(i)), names[i]));
            }
            // return it
            return items;
        }

        public static string GetDescriptionForEnum(this Type type, object value)
        {
            return GetEnumDescription(value.ToString(), type);
        }

        private static string GetEnumDescription(string value, Type type)
        {
            MemberInfo[] memberInfo = type.GetMember(value);

            if (memberInfo != null && memberInfo.Length > 0)
            {
                // default to the first member info, it's for the specific enum value
                var info = memberInfo.First().GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();

                if (info != null)
                    return ((DescriptionAttribute)info).Description;
            }

            // no description - return the string value of the enum
            return value;
        }

        public static void ToggleVisibility(this HtmlGenericControl control, bool toggle)
        {
            string v = toggle ? "block" : "none";
            control.Style["display"] = v;
        }

        public static int IntValue(this System.Web.UI.WebControls.TextBox control)
        {
            return int.Parse(control.Text);
        }
    }
}